/*
 * Copyright 2021 Huawei Technologies Co., Ltd.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package controllers

import (
	"encoding/json"
	"fmt"
	"httpExporter/src/internal"
	"httpExporter/src/model"
	"httpExporter/src/utils"

	"github.com/astaxie/beego"
	log "github.com/sirupsen/logrus"
)

type MainController struct {
	beego.Controller
	FieldOne string `json:"field_one"`
}

func (ctrl *MainController) CallBackRegistery() {
	fmt.Println("In call back register func")
	defer ctrl.ServeJSON() // response type

	var callbackInfo model.CallBackInfo
	err := json.Unmarshal(ctrl.Ctx.Input.RequestBody, &callbackInfo)
	if err != nil {
		log.Error(err, "Unmarshal failed")
		return
	}

	fmt.Println(callbackInfo)

	url := callbackInfo.Url
	node := callbackInfo.Node

	topic, err := utils.GetTopic(node)
	if err != nil {
		log.Error(err, "Getting Topic failed.")
		return
	}
	fmt.Println("Topic:", topic)

	go internal.SendData(url, topic)
	return
}

func (ctrl *MainController) ConfigNodes() {
	fmt.Println("In configNodes func01")
	defer ctrl.ServeJSON() // response type

	nodeInfo := internal.NodeInfo
	err := json.Unmarshal(ctrl.Ctx.Input.RequestBody, &nodeInfo)
	if err != nil {
		log.Error(err, "Unmarshal failed")
		return
	}

	fmt.Println(nodeInfo)
	internal.NodeInfo = nodeInfo
}

func (ctrl *MainController) ConfigMQ() {
	fmt.Println("In config MQ func")
	defer ctrl.ServeJSON() // response type

	mqInfo := internal.MqInfo
	err := json.Unmarshal(ctrl.Ctx.Input.RequestBody, &mqInfo)
	if err != nil {
		log.Error(err, "Unmarshal failed")
		return
	}

	internal.MqInfo = mqInfo
	fmt.Println(internal.MqInfo)
}
